<script setup>
import { ref, onMounted } from 'vue'
import { getFiles, downloadFile, deleteFile, restoreFile } from '@/api/files.js'

const headers = [
  { title: '文件名', key: 'name' },
  { title: '文件类型', key: 'type' },
  { title: '创建者', key: 'createdBy' },
  { title: '标签', key: 'tags' },
  { title: '上次修改时间', key: 'updatedAt' },
  { title: '操作', key: 'actions', sortable: false },
]

// 分页相关状态
const pageNum = ref(1)
const itemsPerPage = ref(10)
const totalItems = ref(0)
const items = ref([])
const loading = ref(false)

// 删除相关状态
const deleteDialog = ref(false)
const selectedItem = ref(null)
const DeleteLoadingMap = ref({})
const DownloadLoadingMap = ref({})

// 还原相关状态
const RestoreLoadingMap = ref({})

const fetchData = async () => {
  loading.value = true
  try {
    const response = await getFiles({
      pageNum: pageNum.value,
      pageSize: itemsPerPage.value,
      deleted: true,
    })
    items.value = response.items
    totalItems.value = response.total
  } catch (error) {
    console.error('Error fetching data:', error)
  } finally {
    loading.value = false
  }
}

const confirmDelete = (item) => {
  DeleteLoadingMap.value[item.id] = true
  selectedItem.value = item
  deleteDialog.value = true
}

const deleteItem = async () => {
  try {
    await deleteFile(selectedItem.value.id)
    fetchData()
  } catch (error) {
    console.error('Error deleting item:', error)
  } finally {
    DeleteLoadingMap.value[selectedItem.value.id] = false
    deleteDialog.value = false
  }
}

const downloadItem = async (item) => {
  DownloadLoadingMap.value[item.id] = true
  try {
    const response = await downloadFile(item.id)
    const blob = new Blob([response.data])
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = item.name + '.' + item.type
    link.click()
    URL.revokeObjectURL(url)
  } catch (error) {
    console.error('Error downloading item:', error)
  } finally {
    DownloadLoadingMap.value[item.id] = false
  }
}

const restoreItem = async (item) => {
  RestoreLoadingMap.value[item.id] = true
  try {
    await restoreFile(item.id)
    fetchData()
  } catch (error) {
    console.error('Error restoring item:', error)
  } finally {
    RestoreLoadingMap.value[item.id] = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <h1>回收站</h1>
  <v-spacer />

  <!-- 表格 -->
  <v-card>
    <v-table>
      <thead>
        <tr>
          <th v-for="header in headers" :key="header.key" class="text-left">
            {{ header.title }}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-if="loading">
          <td :colspan="headers.length" class="text-center">
            <v-progress-circular indeterminate color="primary"></v-progress-circular>
          </td>
        </tr>
        <tr v-else-if="items.length === 0">
          <td :colspan="headers.length" class="text-center">暂无数据</td>
        </tr>
        <tr v-for="item in items" :key="item.id">
          <td>{{ item.name }}</td>
          <td>{{ item.type }}</td>
          <td>{{ item.createdBy }}</td>
          <td>
            <v-chip v-for="tag in item.tags" :key="tag" class="ma-1" color="primary" size="small">
              {{ tag.name }}
            </v-chip>
          </td>
          <td>{{ item.updatedAt }}</td>
          <td>
            <div class="d-flex align-center">
              <!-- 还原 -->
              <template v-if="RestoreLoadingMap[item.id]">
                <v-progress-circular indeterminate size="20" color="primary" class="mr-1" />
              </template>
              <template v-else>
                <v-icon
                  class="mr-2 cursor-pointer"
                  color="success"
                  size="20"
                  @click="restoreItem(item)"
                >
                  mdi-restore
                </v-icon>
              </template>

              <!-- 下载 -->
              <template v-if="DownloadLoadingMap[item.id]">
                <v-progress-circular indeterminate size="20" color="primary" class="mr-1" />
              </template>
              <template v-else>
                <v-icon
                  class="mr-2 cursor-pointer"
                  color="primary"
                  size="20"
                  @click="downloadItem(item)"
                >
                  mdi-file-download
                </v-icon>
              </template>

              <!-- 永久删除 -->
              <template v-if="DeleteLoadingMap[item.id]">
                <v-progress-circular indeterminate size="20" color="error" class="mr-1" />
              </template>
              <template v-else>
                <v-icon class="cursor-pointer" color="error" size="20" @click="confirmDelete(item)">
                  mdi-delete-forever
                </v-icon>
              </template>
            </div>
          </td>
        </tr>
      </tbody>
    </v-table>

    <!-- 分页 -->
    <div class="d-flex justify-center pa-4">
      <v-pagination
        v-model="pageNum"
        :length="Math.ceil(totalItems / itemsPerPage)"
        :total-visible="7"
        @update:model-value="fetchData"
      ></v-pagination>
    </div>
  </v-card>

  <!-- 删除确认对话框 -->
  <v-dialog v-model="deleteDialog" max-width="400">
    <v-card>
      <v-card-title>确认永久删除</v-card-title>
      <v-card-text>确认永久删除该项吗？此操作不可恢复。</v-card-text>
      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn
          color="primary"
          variant="text"
          @click="((deleteDialog = false), (DeleteLoadingMap[selectedItem.id] = false))"
        >
          取消
        </v-btn>
        <v-btn color="error" variant="text" @click="deleteItem">永久删除</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<style scoped>
.cursor-pointer {
  cursor: pointer;
}
</style>
